package java_thinking.unit_17._17_2_6;

import java_thinking.net.mindview.util.RandomGenerator;
import java_thinking.unit_15._15_3.Generator;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * @Desc:   2 一种Generator解决方案
 *          这是一个适配器设计模式，它将Generator适配到Collection的构造器上  难以理解
 *
 *          构造器方法,Collection的构造器接受另外一个Collection，用它来进行初始化：
 *          Collection<Integer> collection =new ArrayList<Integer>(Arrays.asList(1,2,3,4,5));
 *
 *          所有Collection子类型都有一个接受另一个Collection对象的构造器
 *          public ArrayList(Collection<? extends E> c)
 *
 * @author: cww
 * @DateTime: 2019-04-10 22:42
 */

public class CollectionData<T> extends ArrayList<T> {
    public CollectionData(Generator<T> gen,int quantity){
        for (int i =0;i<quantity;i++) {
            add(gen.next());
        }
    }
    public static <T> CollectionData<T> list(Generator<T> gen,int quantity) {
        return new CollectionData<T>(gen,quantity);
    }
}

class Government implements Generator<String> {
    String[] foundation = ("And remember, if the government can do something to someone else, whether you agree or not, what can they do to you".split(" "));
    private int index;
    @Override
    public String next() {
        return foundation[index++];
    }
}


class CollectionDataTest {
    public static void main(String[] args) {
        //LinkedHashSet保留了插入顺序
        Set<String> set = new LinkedHashSet<>(new CollectionData<>(new Government(),20));
        Set<String> set1 = new LinkedHashSet<>(new ArrayList<>());
        System.out.println(set);
        set1.addAll(CollectionData.list(new Government(),12));
        System.out.println(set1);
    }
}

/**
 * 使用第16章定义的RandomGenerator
 */
class CollectionDataGeneration {
    public static void main(String[] args) {
        System.out.println(new ArrayList<String>(CollectionData.list(new RandomGenerator.String(9),10)));
        System.out.println(new HashSet<Integer>(CollectionData.list(new RandomGenerator.Integer(),10)));
    }
}